package com.wenmingliang.blog.controller;

import com.wenmingliang.blog.utils.StringUtils;
import com.wenmingliang.blog.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadController {

    Logger logger = LoggerFactory.getLogger(UploadController.class);
    @CrossOrigin
    @PostMapping
    public Result coversUpload(@RequestParam("image") MultipartFile file) throws Exception {
        String folder = "E:/work/data/upload";
        File imageFolder = new File(folder);
//        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
//                .substring(file.getOriginalFilename().length() - 4));

//        StringUtils.substringAfter(null, *)      = null
//        StringUtils.substringAfter("", *)        = ""
//        StringUtils.substringAfter(*, null)      = ""
//        StringUtils.substringAfter("abc", "a")   = "bc"
//        StringUtils.substringAfter("abcba", "b") = "cba"
//        StringUtils.substringAfter("abc", "c")   = ""
//        StringUtils.substringAfter("abc", "d")   = ""
//        StringUtils.substringAfter("abc", "")    = "abc"
        File f = new File(imageFolder, StringUtils.getRandomString(6)
                + "." + org.apache.commons.lang3.StringUtils.substringAfterLast(file.getOriginalFilename(),"."));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8888/wml/file1/" + f.getName();
            logger.info("上传成功！------------------------------------------------------------------------------");
            return Result.success(imgURL);
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("上传失败！------------------------------------------------------------------------------");
            return Result.fail(200, "上传失败！");
        }
    }
}
